package com.vjwealth.android.nos.http

import android.util.Log
import com.android.volley.NetworkResponse
import com.android.volley.Response
import com.android.volley.toolbox.JsonRequest
import org.json.JSONObject
import com.android.volley.ParseError
import org.json.JSONException
import com.android.volley.toolbox.HttpHeaderParser
import com.vjwealth.android.nos.Constants
import com.vjwealth.android.nos.base.BaseApplication
import java.io.UnsupportedEncodingException
import java.nio.charset.Charset


/**
 * projectName KNOS
 * date 2017/9/28
 * description com.vjwealth.android.nos.http
 */
class BaseStringRequest(method: Int,
                        url: String,
                        stringParams: String,
                        listener: Response.Listener<JSONObject>,
                        errorListener: Response.ErrorListener) : JsonRequest<JSONObject>(method, url, stringParams, listener, errorListener) {

    constructor(method: Int,
                url: String,
                listener: Response.Listener<JSONObject>,
                errorListener: Response.ErrorListener) : this(method, url, "", listener, errorListener)

    override fun getBodyContentType(): String {
        return "application/x-www-form-urlencoded; charset=" + getParamsEncoding()
    }

    override fun getHeaders(): MutableMap<String, String> {
        var headers: MutableMap<String, String> = HashMap()
        headers.put("Authorization", BaseApplication.spInfor!!.getString(Constants.LOGIN_TOKEN))
        headers.put("userChannelType", "Android")
        return headers
    }

    override fun parseNetworkResponse(response: NetworkResponse): Response<JSONObject> {
        try {
            val jsonString = String(response.data, Charset.forName(JsonRequest.PROTOCOL_CHARSET))
            Log.i("TAG", "response = " + jsonString)
            return Response.success(JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response))
        } catch (e: UnsupportedEncodingException) {
            return Response.error(ParseError(e))
        } catch (je: JSONException) {
            return Response.error(ParseError(je))
        }
    }
}